package handler

import (
	"WrStoreServer/config"
	"WrStoreServer/db"
	"WrStoreServer/file"
	"encoding/json"
	"fmt"
	"github.com/sirupsen/logrus"
	"io"
	"io/ioutil"
	"net/http"
	"path/filepath"
	"strings"
	"time"
)

var (
	source      string
	fileHandler *file.FileHandler

	Address string //端口号

	Ptv config.Cfg
)

// 初始化获取资源路径
func init() {
	JsonParse := config.NewJsonStruct()
	Ptv = JsonParse.LoadCfg() //获取结构体信息
	source = Ptv.Dir + "/Source"
	//开启定时删除数据库中的内容
	fileHandler = file.NewFileStruct()
	Address = Ptv.HostAddress //获取端口号
	//开启定时任务保证系统
	go fileHandler.DoWork()
}

/********************数据插入接口*****************/
func (pv *InsertHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	var res Resp
	info := ReqBody{}
	//方法不对
	if r.Method != "POST" {
		res.Code = 405
		res.URL = "url not exist" //代表URL出错了
	}
	body, err := ioutil.ReadAll(r.Body)
	if err != nil && err != io.EOF {
		logrus.Error("处理信息失败 err：", err.Error(), "body:=", string(body))
		res.Code = 406
		res.URL = "url not exist" //代表URL出错了
	} else {
		if err := json.Unmarshal([]byte(string(body)), &info); err != nil {
			res.Code = 406
			res.URL = "url not exist" //代表URL出错了
		} else {
			logrus.Info("接收Robot数据 RobotSn  ", info.RobotSn, "  DataType: ", info.DataType, "  DateTime: ", info.DateTime, "  Msg: ", info.Msg)
			//接收到的数据信息
			url := filepath.Join(info.RobotSn, info.DataType, info.DateTime, info.Msg)
			pFile := filepath.Join(source, url)
			logrus.Info("URL:", url, " Local file path:", pFile)
			//判断文件文件是否存在
			isExist, _ := fileHandler.IsFileExist(pFile)
			if isExist {
				//如果存在，告知存在的目录
				DateTime, err := time.Parse("20060102150405", info.DateTime)
				if err != nil {
					fmt.Println("Failed to parse time:", err)
					return
				}

				var msgs []db.DataInfo
				msgInfo := db.DataInfo{
					RobotSn:  info.RobotSn,
					DataType: info.DataType,
					DateTime: DateTime,
					Msg:      info.Msg,
				}
				msgs = append(msgs, msgInfo)
				//如果存在怎判断是否是jpg数据
				var sql string

				logrus.Info("RobotSn: ", info.RobotSn, "   DataType:", info.DataType, "  DateTime:", DateTime, " Msg:", info.Msg)
				if strings.HasSuffix(info.Msg, ".jpg") && info.Msg != "" && info.DataType == "RGB" {
					//插入RGB数据
					sql = "insert into " + Ptv.DataBase.RGBTable + "(robotSn, dataType, dateTime, msg) values(?,?,?,?)"

				}
				if strings.HasSuffix(info.Msg, ".jpg") && info.Msg != "" && info.DataType == "Depth" {
					//插入Depth深度数据
					sql = "insert into " + Ptv.DataBase.DepthTable + "(robotSn, dataType, dateTime, msg) values(?,?,?,?)"
				}
				if strings.HasSuffix(info.Msg, ".pcd") && info.Msg != "" && info.DataType == "Map" {
					//插入地图
					sql = "insert into " + Ptv.DataBase.MapTable + "(robotSn, dataType, dateTime, msg) values(?,?,?,?)"
				}
				if strings.HasSuffix(info.Msg, ".txt") && info.Msg != "" && info.DataType == "SIG" {
					//插入信令
					sql = "insert into " + Ptv.DataBase.SigTable + "(robotSn, dataType, dateTime, msg) values(?,?,?,?)"
				}
				isOk := db.InsertDataBatches(sql, msgs)

				if isOk {
					res.Code = 200
					res.URL = url
				} else {
					res.Code = 406
					res.URL = "url not exist"
				}
				logrus.Info("插入数据库语句 sql:", sql)
			}
		}
	}
	logrus.Info("响应状态码： ", res.Code, " URL: ", res.URL)
	w.Header().Set("Content-Type", "application/json")
	if err := json.NewEncoder(w).Encode(res); err != nil {
		logrus.Fatal(err)
		return
	}
}
